# Copyright (C) 2006-2008 by Sergio Pistone
# sergio_pistone@yahoo.com.ar
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

require File.expand_path( File.dirname( __FILE__ ) + "/../utils/xmlhash" )
require "tempfile"

module GUI

	@@toolkits = []
	@@run_out_of_process = false
	@@running_out_of_process = false

	def GUI.run_out_of_process?()
		return @@run_out_of_process
	end

	def GUI.set_run_out_of_process( value )
		@@run_out_of_process = value
	end

	def GUI.set_running_out_of_process( value )
		@@running_out_of_process = value
	end

	def GUI.set_toolkit_priority( toolkits )
		toolkits.each() do |toolkit|
			if @@toolkits.include?( toolkit )
				# check if the toolkit is already loaded (and change it's priority)
				@@toolkits.delete( toolkit )
				@@toolkits.insert( 0, toolkit )
				return toolkit
			elsif GUI.load_toolkit( toolkit ) # try to load the toolkit
				@@toolkits.insert( 0, toolkit )
				return toolkit
			end
		end
		return GUI.get_current_toolkit()
	end

	def GUI.load_toolkit( toolkit )
		toolkit = toolkit.downcase()
		if toolkit == "qt" || toolkit == "qt4"
			begin
				return require( File.expand_path( File.dirname( __FILE__ ) + "/gui-qt4" ) )
			rescue LoadError => e
				$stderr << "Error loading Qt4 GUI backend: #{e}\n"
			end
		elsif toolkit == "qt3"
			begin
				return require( File.expand_path( File.dirname( __FILE__ ) + "/gui-qt3" ) )
			rescue LoadError => e
				$stderr << "Error loading Qt3 GUI backend: #{e}\n"
			end
		elsif toolkit == "gtk"
			begin
				return require( File.expand_path( File.dirname( __FILE__ ) + "/gui-gtk" ) )
			rescue LoadError => e
				$stderr << "Error loading GTK GUI backend: #{e}\n"
			end
		elsif toolkit == "tk"
			begin
				return require( File.expand_path( File.dirname( __FILE__ ) + "/gui-tk" ) )
			rescue LoadError => e
				$stderr << "Error loading Tk GUI backend: #{e}\n"
			end
		end
		return false
	end

	def GUI.get_current_toolkit()
		return @@toolkits.length > 0 ? @@toolkits[0].downcase() : nil
	end

	def GUI.create_exchange_file()
		base_filename = Dir.tmpdir() + "/wikilyrics.gui." + $$.to_s()
		filename = nil
		loop do
			filename = base_filename + "." + rand( 65536 ).to_s()
			break unless File.exists?( filename )
		end
		return File.new( filename, "w+" )
	end

	def GUI.show_dialog( dialog_name, values )

		if @@run_out_of_process && ! @@running_out_of_process
			file = GUI.create_exchange_file()
			begin
				XMLHash.write( file, values )
				if ( (ret = system( "ruby", __FILE__, dialog_name, file.path, @@toolkits.join( "," ) )) )
					values = {}
					file.rewind()
					XMLHash.read( file.path, values, false )
				end
				return ret ? values : nil
			ensure
				file.close()
				File.delete( file.path )
			end
		end

		current_toolkit = GUI.get_current_toolkit()

		if current_toolkit == "qt" || current_toolkit == "qt4"
			app = Qt::Application.new( ARGV )
			# FIXME: there's currently a weird bug when using Oxygen style:
			# the first time it's used, it renders and works properly but,
			# when used again, renders badly and generally also crashes.
			if ( ! @@running_out_of_process )
				["plastique", "cleanlooks", "windows", "cde", "motif"].each() do |style|
					break if app.setStyle( style )
				end
			end
			dialog = eval( "QT4::" + dialog_name + ".new( values )" )
			dialog.show()
			app.exec()
		elsif current_toolkit == "qt3"
			app = Qt::Application.new( ARGV )
			dialog = eval( "QT3::" + dialog_name + ".new( values )" )
			app.setMainWidget( dialog )
			app.mainWidget.show()
			app.exec()
		elsif current_toolkit == "gtk"
			dialog = eval( "GTK::" + dialog_name + ".new( values )" )
			dialog.exec()
			Gtk.main()
		elsif current_toolkit == "tk"
			dialog = eval( "TK::" + dialog_name + ".new( values )" )
			dialog.exec()
		else
			return nil
		end

		if dialog.accepted()
			return dialog.values()
		else
			return nil
		end

	end

	def GUI.show_plugins_manager_dialog( values )
		values["script_name"] = "Wiki-Lyrics" if ! values.include?( "script_name" )
		ret = GUI.show_dialog( "PluginsManagerDialog", values )
		values.update( ret ) if ret
		return ret != nil
	end


	def GUI.show_plugins_manager_dialog( values )
		values["script_name"] = "Wiki-Lyrics" if ! values.include?( "script_name" )
		ret = GUI.show_dialog( "PluginsManagerDialog", values )
		values.update( ret ) if ret
		return ret != nil
	end

	def GUI.show_wiki_plugin_dialog( values )
		values["site_name"] = "Wiki-Lyrics" if ! values.include?( "site_name" )
		ret = GUI.show_dialog( "WikiPluginDialog", values )
		values.update( ret ) if ret
		values["submit"] = values["submit"].to_s() == "true"
		values["review"] = values["review"].to_s() == "true"
		values["prompt_autogen"] = values["prompt_autogen"].to_s() == "true"
		values["prompt_no_lyrics"] = values["prompt_no_lyrics"].to_s() == "true"
		return ret != nil
	end

	def GUI.show_submit_song_dialog( values )
		values["year"] = values["year"].to_i()
		values["site_name"] = "Wiki-Lyrics" if ! values.include?( "site_name" )
		ret = GUI.show_dialog( "SubmitSongDialog", values )
		values.update( ret ) if ret
		if values["instrumental"]
			values["lyrics"] = nil
		else
			values["lyrics"] = values["lyrics"].to_s().strip()
		end
		values["reviewed"] = values["reviewed"].to_s() == "true"
		values["instrumental"] = values["instrumental"].to_s() == "true"
		return ret != nil
	end

	def GUI.show_submit_album_dialog( values )
		values["released"] = values["released"].to_s()
		values["site_name"] = "Wiki-Lyrics" if ! values.include?( "site_name" )
		ret = GUI.show_dialog( "SubmitAlbumDialog", values )
		values.update( ret ) if ret
		values["reviewed"] = values["reviewed"].to_s() == "true"
		return ret != nil
	end

	def GUI.show_upload_cover_dialog( values )
		values["site_name"] = "Wiki-Lyrics" if ! values.include?( "site_name" )
		values["year"] = values["year"].to_i()
		ret = GUI.show_dialog( "UploadCoverDialog", values )
		values.update( ret ) if ret
		return ret != nil
	end

	def GUI.show_wiki_fix_pages_dialog( values )
		values["title"] = "Pages fixer" if ! values.include?( "title" )
		GUI.show_dialog( "FixPagesDialog", values )
	end

	def GUI.show_search_lyrics_dialog( values )
		values["year"] = values["year"].to_i()
		ret = GUI.show_dialog( "SearchLyricsDialog", values )
		values.update( ret ) if ret
		return ret != nil
	end

	def GUI.show_lyrics_dialog( values )
		GUI.show_dialog( "ShowLyricsDialog", values )
	end

	def GUI.show_message_dialog( message, title=nil )
		if title
			system( "kdialog", "--icon", "amarok", "--title", title, "--msgbox","<qt>" + message.gsub( "\n", "<br/>" ) + "</qt>" )
		else
			system( "kdialog", "--icon", "amarok", "--msgbox", "<qt>" + message.gsub( "\n", "<br/>" ) + "</qt>" )
		end
	end

	def GUI.show_confirmation_dialog( message, title=nil )
		if title
			system( "kdialog", "--icon", "amarok", "--title", title, "--yesno", "<qt>" + message.gsub( "\n", "<br/>" ) + "</qt>" )
		else
			system( "kdialog", "--icon", "amarok", "--yesno", "<qt>" + message.gsub( "\n", "<br/>" ) + "</qt>" )
		end
		return $? == 0
	end

end

if $0 == __FILE__

	dialog_name = ARGV[0]
	values_file_path = ARGV[1]
	toolkit_priority = ARGV[2].split( "," )

	GUI.set_running_out_of_process( true ) # would cause infinite recursion if not set
	GUI.set_toolkit_priority( toolkit_priority )

	values = {}
	XMLHash.read( values_file_path, values, false )

	ret = GUI.show_dialog( dialog_name, values )

	XMLHash.write( values_file_path, ret ) if ret

	exit( ret ? 0 : 1 )

end
